package com.gjp.processdemo.config;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.Arrays;

/**
 * 跨域配置
 *
 * @author 郭金鹏
 * @version 1.0
 * @date 2019/11/5 16:06
 */
@Configuration
public class CorsConfig {

    /**
     * 跨域配置
     *
     * @return
     */
    @Bean
    public FilterRegistrationBean corsFilterRegistrationBean() {
        CorsConfiguration configuration = new CorsConfiguration();
        // 如果所有的属性不全部配置，一定要执行该方法，初始化
        configuration.applyPermitDefaultValues();
        configuration.setAllowedMethods(Arrays.asList(CorsConfiguration.ALL));
        configuration.setAllowedOrigins(Arrays.asList(CorsConfiguration.ALL));
        configuration.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean<>(
                new CorsFilter(source)
        );
        filterRegistrationBean.setOrder(-10086);
        return filterRegistrationBean;
    }
}
